from __future__ import print_function
import cv2 as cv
import numpy as np
import argparse
import random as rng
from PIL import ImageGrab,Image

rng.seed(12345)


def thresh_callback(val):
    threshold = val
    # 使用Canny检测边缘
    canny_output = cv.Canny(src_gray, threshold, threshold * 2)
    # 找到轮廓
    contours, hierarchy = cv.findContours(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
    # 返回给定形状和类型的新数组，其中填充0。
    drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)
    contours21 = None
    contours22 = None
    for i in range(len(contours)):
        area = cv.contourArea(contours[i])#函数计算面积
        print("i=%s,area: %s" % (i, area))
        if area < 1000:
            continue

        if area == 2900.5:
            contours21 = contours[i]
        if area == 2809.0:
            contours22 = contours[i]

        color = (rng.randint(0, 256), rng.randint(0, 256), rng.randint(0, 256))
        #画出轮廓
        #                图像    轮廓 轮廓index 颜色  线条厚度  线条类型，层级，偏移量
        cv.drawContours(drawing, contours, i, color, 2, cv.LINE_8, hierarchy, 0)

        M = cv.moments(contours[0])  # 计算第一条轮廓的各阶矩,字典形式
        center_x = int(M["m10"] / M["m00"])
        center_y = int(M["m01"] / M["m00"])
        #画出轮廓
        cv.drawContours(drawing, contours, 0, color, 2, cv.LINE_8, hierarchy, 0)
        cv.circle(drawing, (center_x, center_y), 7, 128, -1)#绘制中心点

    # Show in a window
    cv.imshow('Contours', drawing)

    ret = cv.matchShapes(contours21,contours22,1,0.0)
    print( "相识度：%s" % ret )

    #全屏截图
    # im = Image.Image()
    # im.frombytes(drawing.tobytes())
    # img_gray = cv.cvtColor(im, cv.COLOR_BGR2GRAY)
    # #读取目标查找图片
    # template = cv.imread(r'lunguo.png', 0)
    # #匹配，返回相似度
    # res = cv.matchTemplate(img_gray, template, cv.TM_CCOEFF_NORMED)
    # threshold = 0.9
    # loc = np.where(res >= threshold)
    # print("x,y: %s,%s" % (int(loc[1][0]), int(loc[0][0])))



# 加载源图像
parser = argparse.ArgumentParser(description='在你的图像教程中寻找轮廓的代码')
parser.add_argument('--input', help='路径,输入图像de', default='20200207165902.png')
args = parser.parse_args()
src = cv.imread(cv.samples.findFile(args.input))
if src is None:
    print('Could not open or find the image:', args.input)
    exit(0)
# 转换图像为灰色和模糊它
src_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
cv.imshow("gray_win", src_gray)
cv.waitKey()
# src_gray = cv.blur(src_gray, (3, 3))
# cv.imshow("gray_win2", src_gray)
# cv.waitKey()
# Create Window
source_window = 'Source'
cv.namedWindow(source_window)
cv.imshow(source_window, src)
max_thresh = 255
thresh = 100  # 起始阈值???
cv.createTrackbar('Canny Thresh:', source_window, thresh, max_thresh, thresh_callback)
thresh_callback(thresh)
cv.waitKey()
